<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2016/8/11
 * Time: 14:01
 */
namespace SDXApi\Model;
use SDXApi\Service\BuyNowGoodsService;
use SDXApi\Service\PromoteService;
use Think\Image;
use Think\Model;
use Think\Template\Driver\Mobile;

class CategoryModel extends Model
{
    protected $tableName = 'category';


    /*
     * 获取分类列表
     * $cat_id  0-代表显示全部分类，包括子分类
     *
     * */
    public function get_categorylist($cat_id,$is_hd=0,$uid=0,$wid=1){
        $Model=new Model();
        if ($cat_id > 0) {
            $sql = 'SELECT parent_id FROM ' . C('DB_PREFIX') . "category  WHERE cat_id = '$cat_id'";
            $result = $Model->query($sql);
            $parent_id = $result[0]['parent_id'];
        } else {
            $parent_id = 0;
        }
        /*
         判断当前分类中全是是否是底级分类，
         如果是取出底级分类上级分类，
         如果不是取当前分类及其下的子分类
         */
        $sql = 'SELECT count(*) FROM ' . C('DB_PREFIX') . "category WHERE parent_id = '$parent_id' AND is_show = 1 ";
        if ($Model->query($sql) || $parent_id == 0) {
            /* 获取当前分类及其子分类 */
            $sql = 'SELECT c.cat_id,c.cat_name,c.parent_id,c.is_show,c.title_font_weight ' .
                'FROM ' . C('DB_PREFIX') . 'category as c ' .
                "WHERE c.parent_id = 0 AND c.is_show = 1 ORDER BY c.sort_order ASC, c.cat_id ASC";
            $res = $Model->query($sql);
            foreach ($res AS $key=>$row) {
                if ($row['is_show']) {
                    if (isset($row['cat_id']) == isset($row['parent_id'])) {
                        $res[$key]['cat_id_list'] = $this->get_child_tree($row['cat_id']);
                    }
                }
                if($is_hd){
                    $res[$key]['goods_count'] = $this->get_cat_goods_count($row['cat_id'],$wid,$uid);
                }
            }
        }
        if (isset($res)) {
            return array('catelist'=>$res);
        }
    }

    public function get_cat_goods_count($cat_id,$wid=0,$uid=0){
        if(!$wid){
            $wid = C('DEFAULT_WID');
        }
        $category = M('category')->where(array("parent_id"=>$cat_id))->getField('cat_id',true);
        if(count($category)>0){
            $cat_array = $category;
            array_push($cat_array,$cat_id);
            $cat_str = implode(",",$cat_array);
        }else{
            $cat_str = $cat_id;
        }
//        $children = $this->get_children($cat_id);
//        $extension_goods=$this->get_extension_goods($children);

//        $countsql='SELECT count(distinct(g.goods_id)) as goodssum ' .
//            "FROM " . C('DB_PREFIX') . 'goods AS g ' .
//            "LEFT JOIN " . C('DB_PREFIX') . "member_price AS mp " .
//            "ON mp.goods_id = g.goods_id" .
//            ' WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND ' .
//            'g.is_delete = 0 AND (' . $children;

//        $countsql='SELECT count(distinct(goods_id)) as goodssum ' .
//            "FROM " . C('DB_PREFIX') . 'goods_wid_'.$wid.
//            ' WHERE is_on_sale = 1 AND is_alone_sale = 1 AND ' .
//            'is_delete = 0 AND goods_thumb != \'\' AND cat_id in('.$cat_str.')'.
//            'keyword'
//        ;

        $countsql = "select count(distinct(g.goods_id)) as goodssum  from sdx_goods_wid_".$wid." g left join sdx_goods_keywords gk on g.goods_id = gk.goods_id left join (select * from sdx_booking_goods where user_id='".$uid."' and booking_time > ".strtotime("-3 days").") as b  on g.goods_id=b.goods_id where g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.goods_thumb <> '' AND ( g.cat_id in ($cat_str) or gk.keywords in (select t.tag_name from sdx_goods_tag t where t.relation_type in($cat_str)))";


//        if($extension_goods){
//            $countsql.=' OR '.$extension_goods;
//        }
//        $countsql.=')';
        $Model = new Model();
        $rescount=$Model->query($countsql);
        $count = current($rescount);
        if($count['goodssum']>0){
            return$count['goodssum'];
        }else{
            return 0;
        }
    }
    /**
     * 获得指定分类下的商品.
     *
     * @access  public
     * @param   integer $cat_id 分类ID
     * @param   integer $num 数量
     * @param   string $from 来自web/wap的调用
     * @param   string $order_rule 指定商品排序规则
     * @return  array
     */
    public function get_category_goodslist($cat_id, $page = 0, $from = 'web', $order_rule = '', $wid=0, $tag_name=false, $first_letter=false, $uid = 0,$sever_call = false){
    	if(!$wid){
        	$wid = C("DEFAULT_WID");
        }

        if(!$first_letter){
            $cat_array = array();
            $category = M('category')->where(array("parent_id"=>$cat_id))->getField('cat_id',true);
            if(count($category)>0){
                $cat_array = $category;
                array_push($cat_array,$cat_id);
                $cat_str = implode(",",$cat_array);
            }else{
                $cat_str = $cat_id;
            }
            if(empty($cat_id)) returnApiError("错误：分类ID为空");
        }


        $Model = new Model();

        if($first_letter){
            $countsql = "
SELECT
	count(distinct(goods_id)) as goodssum
FROM
	sdx_goods_wid_".$wid."
WHERE
    is_on_sale = 1 AND is_alone_sale = 1 AND is_delete = 0 AND goods_thumb != '' AND Pinyin(goods_name) LIKE '%".$first_letter."%'";
        }else{
            if($from=='hd'){
                $countsql = "select count(distinct(g.goods_id)) as goodssum  from sdx_goods_wid_".$wid." g left join sdx_goods_keywords gk on g.goods_id = gk.goods_id left join (select * from sdx_booking_goods where user_id='".$uid."' and booking_time > ".strtotime("-3 days").") as b  on g.goods_id=b.goods_id where g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.goods_thumb <> '' AND ( g.cat_id in ($cat_str) or gk.keywords in (select t.tag_name from sdx_goods_tag t where t.relation_type in($cat_str)))";
            }else{
                if ($tag_name){

                    $countsql = "
SELECT
	count(distinct(goods_id)) as goodssum
FROM
	sdx_goods_wid_".$wid."
WHERE
    is_on_sale = 1 AND is_alone_sale = 1 AND is_delete = 0 AND goods_thumb != '' AND  keywords LIKE '%".$tag_name."%'";

                }else{
                    $countsql = "
SELECT
	count(distinct(goods_id)) as goodssum
FROM
	sdx_goods_wid_".$wid."
WHERE
    is_on_sale = 1 AND is_alone_sale = 1 AND is_delete = 0  AND goods_thumb != '' AND cat_id in(".$cat_str.")";
                }
            }

        }

        //dump($countsql);
        $rescount = $Model->query($countsql);

        if($rescount[0]['goodssum']>0){
            $pagearr=show_page($rescount[0]['goodssum'],$page);
            if($page>=$pagearr['pagecount']){
                $is_last=1;
            }else{
                $is_last=0;
            }


            if($first_letter){
                $sql = "
SELECT g.*,
IF (g.practical_num > 0, 1, 0) AS real_num,
IF (g.goods_number > 0, 1, 0) AS fic_num,
IF (b.goods_number > 0, 1, 0) AS is_booking
FROM
	sdx_goods_wid_".$wid." as g left join (select goods_number,goods_id from sdx_booking_goods where user_id='".$uid."' and booking_time > ".strtotime("-3 days").") as b  on g.goods_id=b.goods_id 
WHERE
    g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.goods_thumb != '' AND Pinyin(g.goods_name) LIKE '%".$first_letter."%'";

            }else {
                if($from=='hd'){
                    $sql = "select group_concat(distinct g.goods_id),g.*,
                                IF (g.practical_num > 0, 1, 0) AS real_num, 
                                IF (g.goods_number > 0, 1, 0) AS fic_num,
                                IF (b.goods_number > 0, 1, 0) AS is_booking 
                            from sdx_goods_wid_".$wid." g 
                            left join sdx_goods_keywords gk on g.goods_id = gk.goods_id 
                            left join (select goods_number,goods_id from sdx_booking_goods where user_id='".$uid."' and booking_time > ".strtotime("-3 days").") as b  on g.goods_id=b.goods_id
                            where g.is_on_sale = 1 and g.is_alone_sale = 1 and g.is_delete = 0 and g.goods_thumb <> '' and ( g.cat_id in ($cat_str) or gk.keywords in (select t.tag_name from sdx_goods_tag t where t.relation_type in($cat_str)))
                            group by g.goods_id";
                }else{
                    if ($tag_name) {
                        $sql = "
SELECT g.*,
IF (g.practical_num > 0, 1, 0) AS real_num, 
IF (g.goods_number > 0, 1, 0) AS fic_num,
IF (b.goods_number > 0, 1, 0) AS is_booking
FROM
	sdx_goods_wid_".$wid." as g left join (select goods_number,goods_id from sdx_booking_goods where user_id='".$uid."' and booking_time > ".strtotime("-3 days").") as b  on g.goods_id=b.goods_id 
WHERE
    g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.goods_thumb != '' AND g.keywords LIKE '%".$tag_name."%'";
                    } else {
                        $sql = "
SELECT g.*,
IF (g.practical_num > 0, 1, 0) AS real_num,
IF (g.goods_number > 0, 1, 0) AS fic_num,
IF (b.goods_number > 0, 1, 0) AS is_booking
FROM
	sdx_goods_wid_".$wid." as g left join (select goods_number,goods_id from sdx_booking_goods where user_id='".$uid."' and booking_time > ".strtotime("-3 days").") as b  on g.goods_id=b.goods_id 
WHERE
    g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.goods_thumb != '' AND g.cat_id in(".$cat_str.")";
                    }
                }

            }

//             }
//            if($extension_goods){
//                $sql.=' OR '.$extension_goods;
//            }
//
//            $sql.=')';



            $order_rule = empty($order_rule) ? ' ORDER BY real_num DESC,fic_num DESC,sort_order DESC,goods_id DESC ' : $order_rule;

            $sql .= $order_rule;

            if ($page > 0) {
                $sql .= ' LIMIT ' . $pagearr['firstpage'].','.C('page_size');
            }

            //dump($sql);


            $res = $Model->query($sql);

//            dump($res);
//
//            foreach ($res as $key=>$value){
//
//
//                foreach ($res as $key2=>$value2){
//                    if($value['goods_id']==$value2['goods_id']&&$key!=$key2){
//                        unset($res[$key2]);
//                    }
//                }
//            }
//
//            dd($res);
            $goods_list = array();

            foreach ($res AS $idx => $row) {
            	$goods = array();
            	$goods['is_booking'] = $row['is_booking'];
                //促销价
//                $goods['promote_price'] = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
                if ($row['is_buynow'] == 0) {
					$promoteService = new PromoteService();
					$goods = $promoteService->formatPromoteCategoryData($row);

//					if (!isset($goods['promote_price'])) {
//						$goods['promote_message'] = '';
//						$goods['promote_price'] = 0;
//						$goods['promote_start_date'] = 0;
//						$goods['promote_end_date'] = 0;
//					}
                }
//                秒杀价格处理
                else if ($row['is_buynow'] == 1) {
					$buyNowGoodsService = new BuyNowGoodsService($uid, $wid);
					$goods = $buyNowGoodsService->handleBuyNowGoodsCategoryData($row);
					unset($goods['promote_number']);
				}

                $goods['id'] = $row['goods_id'];
                $goods['name'] = $row['goods_name'];
                $goods['brief'] = $row['goods_brief'];
                $goods['market_price'] = trim(D('goods')->get_vip_price_for_all($row['goods_id'],1));    //市场价使用注册会员价
                //$goods['short_name'] = C('goods_name_length') > 0 ? sub_str($row['goods_name'], C('goods_name_length')) : $row['goods_name'];
                $goods['goods_id'] =  $row['goods_id'];
                if($wid){
                    $goods['wid'] = $wid;
                }else{
                    $goods['wid'] =0;
                }
                $goods['goods_brief'] =  $row['goods_brief'];
                $goods['goods_desc'] =  $row['goods_desc'];
                $goods['goods_name'] = $row['goods_name'];
                $goods['shop_price'] = $row['shop_price'];
                $goods['vip_price'] = trim(D('goods')->get_vip_price($row['goods_id'], $uid));
//                vip对比价
                $goods['true_vip_price'] = trim(D('goods')->get_vip_price_for_all($row['goods_id']));

                $goods['is_offline'] = $row['is_offline'];

                if($row['goods_img']){
                    $goods['goods_thumb'] = img_init($row['goods_img']);
                }else{
                    $goods['goods_thumb'] = img_init($row['goods_thumb']);
                }
                $goods['min_buy_num'] =  $row['min_buy_num'];
                $goods['goods_img'] =  img_init($row['goods_img']);
                if($row['spec_value']){
                    $goods['spec_value'] =  $row['spec_value'];
                    $goods['spec_unit'] =  $row['spec_unit'];
                }elseif($row['goods_weight']){
                    $goods['spec_value'] =  $row['goods_weight']*1000;
                    $goods['spec_unit'] =  "g";
                }
                $goods['min_buy_num'] =  $row['min_buy_num'];
                $row['is_presell']=(int)$row['is_presell'];
                if($row['is_presell']!=0){
                    //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
                    $row['is_presell']=D('Goodsstorage')->check_whether_presell($row['goods_id'],$wid);
                }
                if($row['is_presell']){
                    $goods['goods_number'] =  $row['goods_number'];
                    if($row['delivery_type']==1){  //分段发货
                        $Goodspreselltime=D('Goodspreselltime');
                        if($Goodspreselltime->check_shipping_goodspreselltime($row['goods_id'])){//检查预售商品是否设置发货配送时间
                            $preselltimeres=$Goodspreselltime->check_shippingtime($row['goods_id'],time());
                            if($preselltimeres){
                                $goods['preselltimeres']=$preselltimeres;
                            }else{
                                $goods['preselltimeres']=array('delivery_time'=>'');
                            }
                        }else{
                            $goods['preselltimeres']=array('delivery_time'=>'');
                        }
                    }elseif($row['delivery_type']==2){ //定时方式
                        if($row['delivery_cycle']>=0){
                            $gmd=local_date('Y-m-d',gmtime());
                            $goods_presell_time = local_date('Y-m-d H:i:s', local_strtotime($gmd.' +'.$row['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H')));
                            $goods['preselltimeres']=array('delivery_time'=>$goods_presell_time);
                        }else{
                            $goods['preselltimeres']=array('delivery_time'=>'');
                        }
                    }else{
                        $goods['preselltimeres']=array('delivery_time'=>'');
                    }

                }else{
                    $goodsstorage=D('Goodsstorage')->get_warehous_goods($wid,$row['goods_id']);
                    if($goodsstorage){
                        $goods['goods_number']=$goodsstorage['practical_num'];
                    }else{
                        $goods['goods_number']=0;
                    }
                    $goods['preselltimeres']=array('delivery_time'=>'');
                }
                $goods['is_presell'] = $row['is_presell'];
				
                //$goods['url'] = url('goods/index', array('id' => $row['goods_id']));
                
                $goods_list[] = $goods;
            }





            $data = array('goodscatelist'=>$goods_list,'is_bottom'=>$is_last,'page'=>$pagearr,'count'=>$rescount[0]['goodssum']);


                return $data;

            

        }else{
            //未找到商品
                return false;


        }

    }

    public function get_child_tree($tree_id = 0) {
        $three_arr = array();
        $sql = 'SELECT count(*) FROM ' . C('DB_PREFIX') . "category WHERE parent_id = '$tree_id' AND is_show = 1 ";
        $Model=new Model();
        $res = $Model->query($sql);
        if ($res || $tree_id == 0) {
            $child_sql = 'SELECT c.cat_id, c.cat_name, c.parent_id, c.is_show,c.title_font_weight ' .
                'FROM ' . C('DB_PREFIX') . 'category as c ' .
                " WHERE c.parent_id = '$tree_id' AND c.is_show = 1 GROUP BY c.cat_id ORDER BY c.sort_order ASC, c.cat_id ASC";
            $res = $Model->query($child_sql);
            foreach ($res AS $key=>$row) {

                if (isset($row['cat_id']) != NULL) {
                    $res[$key]['cat_id_list'] = $this->get_child_tree($row['cat_id']);
                }
            }
        }
        return $res;
    }

    /**
     * 调用指定分类下子分类的商品的缩略图，条件:精品，排序规则:按推荐排序，默认按最大商品ID
     * @param  [type] $cat_id 　add by 20160204
     * @return [type]
     */
    public function get_cat_goods_img($cat_id){
        $extension_goods_array = '';
        if($cat_id){
            $where['cat_id']=array('in',array($cat_id));
            $res=M('goods_cat')->where($where)->field('goods_id')->select();
            if ($res !== false) {
                $arr = array();
                foreach ($res as $key => $value) {
                    $arr[] = $value['goods_id'];
                }
            }
        }
        $extension_goods_array =  db_create_in($arr, 'g.goods_id');
        $where = "g.is_on_sale = 1 AND g.is_alone_sale = 1 AND " . "g.is_delete = 0 ";
        if ($cat_id !== 0) {
            $where .= "AND(g.cat_id = $cat_id OR " .$extension_goods_array .")";

        }
        /* 获得商品列表 */
        $sql = 'SELECT g.goods_id,  g.goods_thumb as cat_img , g.goods_img ' . 'FROM ' . C('DB_PREFIX') . 'goods AS g ' . ' LEFT JOIN ' . C('DB_PREFIX') . 'touch_goods AS xl ' . ' ON g.goods_id=xl.goods_id ' .
            ' LEFT JOIN ' . C('DB_PREFIX') . 'member_price AS mp ' . "ON mp.goods_id = g.goods_id " . "WHERE $where GROUP BY g.goods_id ORDER BY g.sort_order DESC";
        $Model=new Model();
        $res = $Model->query($sql);
        return $res[0]['cat_img'];
    }
    /**
     * 获取一级分类信息
     */
    public function get_top_category() {
        $sql = 'SELECT c.cat_id,c.cat_name,c.parent_id,c.is_show,t.cat_image ' .
            'FROM ' . C('DB_PREFIX') . 'category as c ' .
            'left join ' . C('DB_PREFIX') . 'touch_category as t on t.cat_id = c.cat_id ' .
            "WHERE c.parent_id = 0 AND c.is_show = 1 ORDER BY c.sort_order ASC, c.cat_id ASC";
        $Model=new Model();
        $res = $this->query($sql);
        foreach ($res AS $row) {
            if ($row['is_show']) {
                $cat_arr[$row['cat_id']]['id'] = $row['cat_id'];
                $cat_arr[$row['cat_id']]['name'] = $row['cat_name'];
                $cat_arr[$row['cat_id']]['cat_image'] = $row['cat_image'];
                //$cat_arr[$row['cat_id']]['url'] = url('category/index', array('id' => $row['cat_id']));
            }
        }
        return $cat_arr;
    }

    /**
     * 获得指定分类下所有底层分类的ID
     *
     * @access  public
     * @param   integer     $cat        指定的分类ID
     * @return  string
     */
    public function get_children($cat = 0)
    {
        return 'g.cat_id ' . db_create_in(array_unique(array_merge(array($cat), array_keys($this->cat_list($cat, 0, false)))));
    }


    /**
     * 获得指定分类下的子分类的数组
     *
     * @access  public
     * @param   int     $cat_id     分类的ID
     * @param   int     $selected   当前选中分类的ID
     * @param   boolean $re_type    返回的类型: 值为真时返回下拉列表,否则返回数组
     * @param   int     $level      限定返回的级数。为0时返回所有级数
     * @param   int     $is_show_all 如果为true显示所有分类，如果为false隐藏不可见分类。
     * @return  mix
     */
    public function cat_list($cat_id = 0, $selected = 0, $re_type = true, $level = 0, $is_show_all = true)
    {
        $Model=new Model();
        static $res = NULL;

        if ($res === NULL)
        {
            $sql = "SELECT c.cat_id, c.cat_name, c.measure_unit, c.parent_id, c.is_show, c.show_in_nav, c.grade, c.sort_order, COUNT(s.cat_id) AS has_children ".
                'FROM ' . C('DB_PREFIX'). "category AS c ".
                "LEFT JOIN " . C('DB_PREFIX') . "category AS s ON s.parent_id=c.cat_id ".
                "GROUP BY c.cat_id ".
                'ORDER BY c.parent_id, c.sort_order ASC';
            $res = $Model->query($sql);

            $sql = "SELECT cat_id, COUNT(*) AS goods_num " .
                " FROM " . C('DB_PREFIX') .
                "goods WHERE is_delete = 0 AND is_on_sale = 1 " .
                " GROUP BY cat_id";
            $res2 = $Model->query($sql);

            $sql = "SELECT gc.cat_id, COUNT(*) AS goods_num " .
                " FROM " . C('DB_PREFIX') . "goods_cat AS gc , " . C('DB_PREFIX') . "goods AS g " .
                " WHERE g.goods_id = gc.goods_id AND g.is_delete = 0 AND g.is_on_sale = 1 " .
                " GROUP BY gc.cat_id";
            $res3 = $Model->query($sql);

            $newres = array();
            foreach($res2 as $k=>$v)
            {
                $newres[$v['cat_id']] = $v['goods_num'];
                foreach($res3 as $ks=>$vs)
                {
                    if($v['cat_id'] == $vs['cat_id'])
                    {
                        $newres[$v['cat_id']] = $v['goods_num'] + $vs['goods_num'];
                    }
                }
            }

            foreach($res as $k=>$v)
            {
                $res[$k]['goods_num'] = !empty($newres[$v['cat_id']]) ? $newres[$v['cat_id']] : 0;
            }

        }

        if (empty($res) == true)
        {
            return $re_type ? '' : array();
        }

        $options = $this->cat_options($cat_id, $res); // 获得指定分类下的子分类的数组

        $children_level = 99999; //大于这个分类的将被删除
        if ($is_show_all == false)
        {
            foreach ($options as $key => $val)
            {
                if ($val['level'] > $children_level)
                {
                    unset($options[$key]);
                }
                else
                {
                    if ($val['is_show'] == 0)
                    {
                        unset($options[$key]);
                        if ($children_level > $val['level'])
                        {
                            $children_level = $val['level']; //标记一下，这样子分类也能删除
                        }
                    }
                    else
                    {
                        $children_level = 99999; //恢复初始值
                    }
                }
            }
        }

        /* 截取到指定的缩减级别 */
        if ($level > 0)
        {
            if ($cat_id == 0)
            {
                $end_level = $level;
            }
            else
            {
                $first_item = reset($options); // 获取第一个元素
                $end_level  = $first_item['level'] + $level;
            }

            /* 保留level小于end_level的部分 */
            foreach ($options AS $key => $val)
            {
                if ($val['level'] >= $end_level)
                {
                    unset($options[$key]);
                }
            }
        }

        if ($re_type == true)
        {
            $select = '';
            foreach ($options AS $var)
            {
                $select .= '<option value="' . $var['cat_id'] . '" ';
                $select .= ($selected == $var['cat_id']) ? "selected='ture'" : '';
                $select .= '>';
                if ($var['level'] > 0)
                {
                    $select .= str_repeat('&nbsp;', $var['level'] * 4);
                }
                $select .= htmlspecialchars(addslashes($var['cat_name']), ENT_QUOTES) . '</option>';
            }

            return $select;
        }
        else
        {
            /*foreach ($options AS $key => $value)
            {
                $options[$key]['url'] = build_uri('category', array('cid' => $value['cat_id']), $value['cat_name']);
            }*/

            return $options;
        }
    }

    /**
     * 过滤和排序所有分类，返回一个带有缩进级别的数组
     *
     * @access  private
     * @param   int     $cat_id     上级分类ID
     * @param   array   $arr        含有所有分类的数组
     * @param   int     $level      级别
     * @return  void
     */
    public function cat_options($spec_cat_id, $arr)
    {
        static $cat_options = array();

        if (isset($cat_options[$spec_cat_id]))
        {
            return $cat_options[$spec_cat_id];
        }

        if (!isset($cat_options[0]))
        {
            $level = $last_cat_id = 0;
            $options = $cat_id_array = $level_array = array();
            while (!empty($arr))
            {
                foreach ($arr AS $key => $value)
                {
                    $cat_id = $value['cat_id'];
                    if ($level == 0 && $last_cat_id == 0)
                    {
                        if ($value['parent_id'] > 0)
                        {
                            break;
                        }

                        $options[$cat_id]          = $value;
                        $options[$cat_id]['level'] = $level;
                        $options[$cat_id]['id']    = $cat_id;
                        $options[$cat_id]['name']  = $value['cat_name'];
                        unset($arr[$key]);

                        if ($value['has_children'] == 0)
                        {
                            continue;
                        }
                        $last_cat_id  = $cat_id;
                        $cat_id_array = array($cat_id);
                        $level_array[$last_cat_id] = ++$level;
                        continue;
                    }

                    if ($value['parent_id'] == $last_cat_id)
                    {
                        $options[$cat_id]          = $value;
                        $options[$cat_id]['level'] = $level;
                        $options[$cat_id]['id']    = $cat_id;
                        $options[$cat_id]['name']  = $value['cat_name'];
                        unset($arr[$key]);

                        if ($value['has_children'] > 0)
                        {
                            if (end($cat_id_array) != $last_cat_id)
                            {
                                $cat_id_array[] = $last_cat_id;
                            }
                            $last_cat_id    = $cat_id;
                            $cat_id_array[] = $cat_id;
                            $level_array[$last_cat_id] = ++$level;
                        }
                    }
                    elseif ($value['parent_id'] > $last_cat_id)
                    {
                        break;
                    }
                }

                $count = count($cat_id_array);
                if ($count > 1)
                {
                    $last_cat_id = array_pop($cat_id_array);
                }
                elseif ($count == 1)
                {
                    if ($last_cat_id != end($cat_id_array))
                    {
                        $last_cat_id = end($cat_id_array);
                    }
                    else
                    {
                        $level = 0;
                        $last_cat_id = 0;
                        $cat_id_array = array();
                        continue;
                    }
                }

                if ($last_cat_id && isset($level_array[$last_cat_id]))
                {
                    $level = $level_array[$last_cat_id];
                }
                else
                {
                    $level = 0;
                }
            }
            $cat_options[0] = $options;
        }
        else
        {
            $options = $cat_options[0];
        }

        if (!$spec_cat_id)
        {
            return $options;
        }
        else
        {
            if (empty($options[$spec_cat_id]))
            {
                return array();
            }

            $spec_cat_id_level = $options[$spec_cat_id]['level'];

            foreach ($options AS $key => $value)
            {
                if ($key != $spec_cat_id)
                {
                    unset($options[$key]);
                }
                else
                {
                    break;
                }
            }

            $spec_cat_id_array = array();
            foreach ($options AS $key => $value)
            {
                if (($spec_cat_id_level == $value['level'] && $value['cat_id'] != $spec_cat_id) ||
                    ($spec_cat_id_level > $value['level']))
                {
                    break;
                }
                else
                {
                    $spec_cat_id_array[$key] = $value;
                }
            }
            $cat_options[$spec_cat_id] = $spec_cat_id_array;

            return $spec_cat_id_array;
        }
    }

    /**
     * 获得所有扩展分类属于指定分类的所有商品ID
     *
     * @access  public
     * @param   string $cat_id     分类查询字符串
     * @return  string
     */
    public function get_extension_goods($cats) {
        $extension_goods_array = '';
        $sql = 'SELECT goods_id FROM ' . C('DB_PREFIX') . "goods_cat AS g WHERE $cats";
        $Model=new Model();
        $res = $Model->query($sql);
        if ($res !== false) {
            $arr = array();
            foreach ($res as $key => $value) {
                $arr[] = $value['goods_id'];
            }
        }
        if(count($arr)>0){
            return db_create_in($arr, 'g.goods_id');
        }
    }


    /**
     * 查询全部分类列表
     * @param type $area_id
     */
    public function get_all_cat_list() {
        $sql = "SELECT c.cat_id, c.cat_name, c.measure_unit, c.parent_id, c.is_show, c.show_in_nav, c.grade, c.sort_order, COUNT(s.cat_id) AS has_children " .
            'FROM ' . C('DB_PREFIX') . "category AS c " .
            "LEFT JOIN " . C('DB_PREFIX') . "category AS s ON s.parent_id=c.cat_id " .
            "GROUP BY c.cat_id " .
            'ORDER BY c.parent_id, c.sort_order ASC';
        $Model=new Model();
        $res = $Model->query($sql);

        $sql = "SELECT cat_id, COUNT(*) AS goods_num " .
            " FROM " . C('DB_PREFIX') . "goods WHERE is_delete = 0 AND is_on_sale = 1 " .
            " GROUP BY cat_id";
        $res2 = $Model->query($sql);

        $sql = "SELECT gc.cat_id, COUNT(*) AS goods_num " .
            " FROM " . C('DB_PREFIX') . "goods_cat AS gc , " .  C('DB_PREFIX') . "goods AS g " .
            " WHERE g.goods_id = gc.goods_id AND g.is_delete = 0 AND g.is_on_sale = 1 " .
            " GROUP BY gc.cat_id";
        $res3 = $Model->query($sql);

        $newres = array();
        if (is_array($res2))
            foreach ($res2 as $k => $v) {
                $newres[$v['cat_id']] = $v['goods_num'];
                if (is_array($res3))
                    foreach ($res3 as $ks => $vs) {
                        if ($v['cat_id'] == $vs['cat_id']) {
                            $newres[$v['cat_id']] = $v['goods_num'] + $vs['goods_num'];
                        }
                    }
            }

        foreach ($res as $k => $v) {
            $res[$k]['goods_num'] = !empty($newres[$v['cat_id']]) ? $newres[$v['cat_id']] : 0;
        }

        return $res;
    }


    /**
     * 返回搜索结果的所属分类
     * @param $keyword
     * @return mixed
     */
    public function get_search_cat_list($keyword)
    {
        $where ['g.goods_name'] = array(
            'like',
            '%' . $keyword . '%'
        );
        $where ['g.is_on_sale'] = 1;
        $where ['g.is_alone_sale'] = 1;
        $where ['g.is_delete'] = 0;
        $where ['g.goods_thumb'] = array("neq","");
//        $where['g.sources'] = array('neq', 891);

        $data = $this
            ->field('sdx_category.cat_name, sdx_category.cat_id')
            ->join('sdx_goods as g ON g.cat_id = sdx_category.cat_id')
            ->where($where)
            ->group('sdx_category.cat_name')
            ->select();

        return $data;
    }

	/**
	 * 返回所有显示分类
	 * Created by Jerry
	 * @return mixed
	 */
    public function findCategoryList()
	{
		$where = array(
			'is_show'	=>	1
		);
//        $is_h5 = I('post.is_h5'); //h5
//        if(!$is_h5){
//            $where['_string']= "link='' and keywords=''";  //临时屏蔽部分没有商品的分类，Android和ios更新后去掉此条件
//        }

		$field = 'cat_id, cat_name, cat_desc, parent_id, sort_order, template_file, measure_unit, show_in_nav, style, grade, filter_attr, title_font_weight, cat_image, link, search_type, keywords, link';

		return $this->field($field)->where($where)->order('sort_order')->group('cat_id')->select();
	}

	/**
	 * Created by Jerry
	 * @param $catId
	 * @return mixed
	 */
	public function findCategoryByCatId($catId)
	{
		$where = array(
			'c.is_show'		=>	1,
			'c.parent_id'	=>	$catId,
		);

		$field = 'c.cat_id, c.cat_name, c.cat_desc, c.parent_id, c.sort_order, c.template_file, c.measure_unit, c.show_in_nav, c.style, c.grade, c.filter_attr, c.title_font_weight, tc.cat_image';

		return $this->alias('c')
			->field($field)
			->join('LEFT JOIN __TOUCH_CATEGORY__ as tc ON c.cat_id = tc.cat_id')
			->where($where)
			->select();
	}

    /**
     * 获取分类级别id
     * Created by caicm
     * @param $catId  分类id
     * @param $level 级别 $level=1获取1级分类id
     * @return int
     */
    protected $cat_ids;
	public function findLevelCatId($catId, $level=1){

        $where = array(
            'cat_id' => $catId
        );

        $data = $this->field('cat_id,parent_id')->where($where)->find();
        $this->cat_ids[] = $data['cat_id'];

        if($data['parent_id'])
            $this->findLevelCatId($data['parent_id']);

        krsort($this->cat_ids);
        foreach ($this->cat_ids as $val){
            $id_list[] = $val;
        }

        return $id_list[$level-1];
    }

    /**
     * @author Jerry
     * @return mixed
     */
    public function getCategoryAds()
    {
        $time = gmtime();
        $sql = "SELECT
                    ad.ad_name,
                    ad.ad_link,
                    c.cat_id,
                    c.cat_name,
                    ad.ad_code
                FROM
                    sdx_category AS c,
                    sdx_ad_position AS ap,
                    sdx_ad AS ad
                WHERE
                    c.cat_id = ap.goods_category
                AND ap.position_id = ad.position_id
                AND ad.enabled = 1
                AND c.parent_id = 0
                AND c.is_show = 1
                AND ad.start_time < '{$time}'
                AND ad.end_time > '{$time}'";

        return $this->query($sql);
    }

    /**
     * @author Jerry
     * @param int $category_id
     * @return mixed
     */
    public function getCategoryParentCountNumber($category_id = 0)
    {
        $where = array(
            'parent_id' =>  $category_id,
            'is_show'   =>  1,
        );

        return $this->where($where)->count();
    }
}